import { Fragment, useEffect } from 'react';

import { useCreateOrderModal } from '@/entities/course';
import { Container, Wrapper } from '@/shared/ui';
import { Footer } from '@/widgets/Footer';
import { Header } from '@/widgets/Header';
import { useRouter } from 'next/router';

import { useCourseBlocks } from './config';
import cs from './Course.module.scss';
import { ActionCard } from './ui/ActionCard';
import { CourseInformation } from './ui/CourseInformation';

export const Course = () => {
  const { actions, blocks, course, isFetching, isSuccess } = useCourseBlocks();
  const router = useRouter();
  const { handleBuy } = useCreateOrderModal(router.query.id as string);
  useEffect(() => {
    if (router.query.buy) {
      router.replace(router.asPath.replace('?buy=true', '')).then(() => {
        handleBuy();
      });
    }
  }, []);
  if (!actions && !blocks && !course && !isFetching && !isSuccess) {
    return <></>;
  }
  return (
    <div className={cs.container}>
      <Header className={cs.header} />
      <Wrapper className={cs.wrapper}>
        <Container className={cs.wrap}>
          <div className={cs.page}>
            <div className={cs.card}>
              <div className={cs.floating_card_container}>
                <ActionCard
                  actions={Object.entries(actions).map(([name, action]) => (
                    <Fragment key={name}>{action}</Fragment>
                  ))}
                  blocks={blocks}
                  course={course}
                  isFetching={isFetching}
                  isSuccess={isSuccess}
                />
              </div>
            </div>
            <CourseInformation blocks={blocks} course={course} />
          </div>
        </Container>
      </Wrapper>
      <Footer className={cs.footer} />
    </div>
  );
};
